package com.suse.warmstill.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.suse.warmstill.common.model.CallResult;
import com.suse.warmstill.common.model.ListPageModel;
import com.suse.warmstill.common.utils.UserIdThreadLocal;
import com.suse.warmstill.entity.Comment;
import com.suse.warmstill.entity.TbUserinfo;
import com.suse.warmstill.mapper.TbUserinfoMapper;
import com.suse.warmstill.service.CommentService;
import com.suse.warmstill.mapper.CommentMapper;
import com.suse.warmstill.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author ADMIN
 * @description 针对表【comment】的数据库操作Service实现
 * @createDate 2023-02-04 15:41:12
 */
@Slf4j
@Service
public class CommentServiceImpl
        implements CommentService {

    @Resource
    private CommentMapper commentMapper;

    @Resource
    private TbUserinfoMapper userinfoMapper;


    @Override
    public ListPageModel<CommentRootVo> listAllComments(Long articleId, int size, int current) {

        List<CommentRootVo> list = new ArrayList<>();
        Page<Comment> commentPage = new Page<>(current, size);
        LambdaQueryWrapper<Comment> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Comment::getRoot, "0").eq(Comment::getParent, "0");
        wrapper.eq(Comment::getArticleId,articleId);

        final Page<Comment> page = commentMapper.selectPage(commentPage, wrapper);

        List<String> collect = page.getRecords().stream().map(Comment::getId).map((id) -> {

            return String.valueOf(id);
        }).collect(Collectors.toList());
        for (String rooId :
                collect) {
            list.add(listComments(rooId));
        }


        ListPageModel<CommentRootVo> listPageModell = new ListPageModel<>();
        listPageModell.setList(list);
        listPageModell.setPageSize((int) page.getSize());
        listPageModell.setCurrentPage((int) page.getCurrent());
        listPageModell.setDataSize((int) page.getTotal());
        listPageModell.setPageCount((int) page.getPages());

        return listPageModell;
    }

    @Override
    public CommentRootVo listComments(String rootId) {


        //1、先拼装 replies
        /*
         *
         *
         * */
        CommentRootVo commentRootVo = new CommentRootVo();


        List<Reply> replies = new ArrayList<>();

        List<Comment> commentList = commentMapper.selectAllByRoot(rootId);

        for (Comment comment : commentList
        ) {
            Reply reply = createReply(comment);
            replies.add(reply);
            commentRootVo.setCount(commentRootVo.getCount() + 1);
        }
        commentRootVo.setReplies(replies);

        /*
         * 1、如果是一级评论就要拼接root
         *
         * */


        Root root = createRoot(rootId);
        commentRootVo.setRoot(root);
        return commentRootVo;
    }


    @Override
    public CallResult<CommentVo> save(CommentPostVo commentPostVo) {


        Integer replyId = Integer.valueOf(Math.toIntExact(UserIdThreadLocal.get()));


        Comment comment = new Comment();
        comment.setArticleId(commentPostVo.getArticleId());
        /*
         * level设置
         * 如果 parent 和root = 0则 level 为0，一级评论
         * 否则 查询 当前parent 相同的有多少，然后 +1
         * */
        if (commentPostVo.getParent().equals("0")) {
            comment.setLevel(0);
        } else {
            int levelAll = commentMapper.selectCountByParentId(commentPostVo.getParent());
            comment.setLevel(levelAll + 1);
        }


        comment.setRoot(commentPostVo.getRoot());
        comment.setMessage(commentPostVo.getMessage());
        comment.setParent(commentPostVo.getParent());
        comment.setReplyedId(commentPostVo.getReplyedId());
        comment.setReplyId(replyId);
        commentMapper.insert(comment);


        //组装返回数据
        Comment commentreturn = commentMapper.selectById(comment.getId());
        if (Objects.isNull(commentreturn)) {
            throw new RuntimeException("发布评论失败");
        }

        final CommentVo commentVo = new CommentVo();
        commentVo.setId(commentreturn.getId());
        commentVo.setArticleId(commentreturn.getArticleId());

        commentVo.setRoot(commentreturn.getRoot());
        commentVo.setParent(commentreturn.getParent());
        commentVo.setReplyId(commentreturn.getReplyId());


        commentVo.setReply(createReply(commentreturn));


        return CallResult.success(commentVo);
    }


    private Root createRoot(String rootId) {

        Comment comment = commentMapper.selectById(rootId);
        Root root = new Root();

        root.setId(Integer.valueOf(rootId));
        root.setRoot(comment.getRoot());
        root.setParent(comment.getParent());
        root.setArticleId(comment.getArticleId());
        root.setReplyId(comment.getReplyId());

        root.setMember(createUserReply(comment.getReplyId()));

        Content content = new Content();
        content.setMessage(comment.getMessage());

        root.setContent(content);


        root.setCreateTime(comment.getCreateTime());


        return root;
    }


    private Reply createReply(Comment commentreturn) {
        Reply reply = new Reply();
        reply.setId(commentreturn.getId());
        reply.setArticleId(commentreturn.getArticleId());
        reply.setCreateTime(commentreturn.getCreateTime());
        reply.setRoot(commentreturn.getRoot());
        reply.setParent(commentreturn.getParent());
        reply.setReplyId(commentreturn.getReplyId());


        /*
         * 如果不是1级评论，就设置子类的 members
         * */
        Content content = null;
        if (!commentreturn.getParent().equals("0") && !commentreturn.getRoot().equals("0")) {
            content = createContent(commentreturn.getReplyedId());
            content.getMembers().get(0).setCurrent_level(commentMapper.selectById(commentreturn.getParent()).getLevel());

        } else {
            content = new Content();
        }


        content.setMessage(commentreturn.getMessage());


        reply.setContent(content);


        //设置当前的评论的level
        final UserReply userReply = createUserReply(commentreturn.getReplyId());
        userReply.setCurrent_level(commentreturn.getLevel());
        reply.setMember(userReply);

        return reply;
    }

    /*
     * 被评论的id
     * */
    private Content createContent(Integer replyedId) {
        final Content content = new Content();

        final ArrayList<UserReply> userReplies = new ArrayList<>();
        final UserReply userReply = createUserReply(replyedId);
        userReplies.add(userReply);
        content.setMembers(userReplies);
        content.setAt_name_to_mid(new at_name_to_mid(userReply.getUsername(), Math.toIntExact(userReply.getId())));

        return content;

    }


    private UserReply createUserReply(Integer id) {
        final LambdaQueryWrapper<TbUserinfo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(TbUserinfo::getUserId, id);
        final TbUserinfo userinfo = userinfoMapper.selectOne(wrapper);

        final UserReply userReply = new UserReply();
        userReply.setUsername(userinfo.getNickName());
        userReply.setAvatar(userinfo.getPhotoPath());
        userReply.setId(Long.valueOf(id));
        return userReply;
    }

}




